package cc.ttiot.utils;

import java.util.Arrays;

/**
 * @Description: TODO
 * @Author WangSuheng
 * @Date 2021/10/4 1:29
 * @Version 1.0
 */
public class StringUtils {
    //是否为空白
    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                // 看是否有空白字符
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }
            return true;
        } else {
            return true;
        }
    }

    //验证id是否合法(由数字和下划线组成)
    public static boolean validate(String id) {
        return id.matches("^(\\d+_)*\\d+$");
    }

    //解析doorId
    public static long getDoorId() {
        String s = PropertiesUtils.getProperty("doorId");
        int[] temp = resolve(s);
        //TODO 改成抛异常
        if (temp.length != 8) {

        }

        long res = 0;
        res += (long) temp[0] << 60;
        res += (long) temp[1] << 52;
        res += (long) temp[2] << 44;
        res += (long) temp[3] << 36;
        res += (long) temp[4] << 32;
        res += (long) temp[5] << 24;
        res += (long) temp[6] << 8;
        res += (long) temp[7];
        return res;
    }

    //解析sensorId
    public static int[] getSensorId() {
        String s = PropertiesUtils.getProperty("sensorId");
        int[] res = resolve(s);
        //TODO 改成抛异常
        for (int i : res) {
            if (i <= 0 || i > 255) {

            }
        }
        return res;
    }

    //将一个以下划线将数字分开的String转换成int数组
    //用于解析防护门配置文件中的doorid和sensorid
    public static int[] resolve(String id) {
        if (id == null || !validate(id)) {
            //TODO 改成抛异常
            System.out.println("id不合法");
            return new int[0];
        }
        String[] s = id.split("_");
        int[] res = new int[s.length];
        for (int i = 0; i < s.length; i++) {
            res[i] = Integer.parseInt(s[i]);
        }

        return res;
    }

    //1个short转换成2个byte
    public static byte[] short2byte(short s) {
        byte[] b = new byte[2];
        for (int i = 0; i < 2; i++) {
            int offset = 16 - (i + 1) * 8;
            b[i] = (byte) ((s >> offset) & 0xff);
        }
        return b;
    }

    //2个byte转换成1个short
    public static short byte2short(byte[] b) {
        short l = 0;
        for (int i = 0; i < 2; i++) {
            l <<= 8;
            l |= (b[i] & 0xff);
        }
        return l;
    }


}
